<template>
  <div id='QualityStageType'>
    <Breadcrumb content='阶段类型' />
    <div class='bodyContent'>
      <el-tabs type='border-card'>
        <el-tab-pane label='阶段类型'>
          <Splitpanes class='area'>
            <Pane size='55'>
              <vxe-toolbar perfect>
                <template #buttons>
                  <span class='smallToolTitle'>名称模糊查找:</span>
                  <vxe-input v-model='form.antName' placeholder='名称' class='vxeInputSearch' type='text' clearable
                             @clear='findPageList'></vxe-input>
                  <vxe-button type='text' icon='vxe-icon-search' class='button-blue SearchBtn' content='查询'
                              :loading='loading' @click='findPageList'></vxe-button>
                  <vxe-button type='text' icon='vxe-icon-add' class='button-blue' content='新增'
                              @click='insertEvent'></vxe-button>
                </template>
              </vxe-toolbar>

              <div class='tableBox'>
                <vxe-table ref='tableRef' border='inner' align='left' class='mytable-scrollbar' height='auto'
                           :data='stageTypeList'
                           :expand-config='{ expandAll: true, reserve: true }'
                           :row-config='{ isCurrent: true, isHover: true }'
                           :keyboard-config='{ isArrow: true, isTab: true, isEdit: true }'
                           :edit-config="{ trigger: 'dblclick', mode: 'row', showStatus: true }"
                           resizable show-overflow keep-source @current-change='roleRowClick'>
                  <vxe-column type='checkbox' width='30px'></vxe-column>
                  <vxe-column field='code' title='阶段编码'></vxe-column>
                  <vxe-column field='name' title='阶段名称'></vxe-column>
                  <vxe-column field='isEnable' title='是否启用'>
                    <template #default='{ row }'>
                      <el-tag type='danger' v-if='row.isEnable === 0'>否</el-tag>
                      <el-tag type='success' v-else-if='row.isEnable === 1'>是</el-tag>
                      <span v-else>——</span>
                    </template>
                  </vxe-column>
                  <vxe-column title='操作' width='200' show-overflow>
                    <template #default='{ row }'>
                      <vxe-button status="primary" content="模版" class="modelViewBtn"  icon='vxe-icon-eye-fill' @click='editTemplate(row)'></vxe-button>
                      <vxe-button  status="danger" content="删除"  class="deleteBtn" icon='vxe-icon-delete' @click='removeEvent(row)'>
                      </vxe-button>
                    </template>
                  </vxe-column>
                </vxe-table>
              </div>
            </Pane>


            <el-dialog title='模板设置' :show-close='false'
                       v-model='showTemplateDialog' append-to-body
                       class='dialogExcel' top='6vh'
                       :close-on-click-modal='false'
                       style='height:800px; width: 1500px'>
              <LuckyExcelForm ref='refFormData' style='height: 670px;' />
              <div class='dialog-footer flex right justify-end' style='margin-top: 10px;'>
                <el-button type="primary" v-if='isEditTemplate' @click='submitTemplateDialog'>提交</el-button>
                <el-button type="primary"  @click='closeTemplateDialog'>取消</el-button>
              </div>
            </el-dialog>

            <Pane size='45'>
              <el-tabs type='border-card'>
                <el-tab-pane label='基本信息'>
                  <el-form ref='formRef' :model='formData' label-width='90px' class='form-input-m' inline-message>
                    <el-row :gutter='20'>
                      <el-col :span='20'>
                        <el-form-item label='编码' prop='code'>
                          <el-input v-model='formData.code' placeholder='请输入编码' clearable></el-input>
                        </el-form-item>
                      </el-col>
                    </el-row>

                    <el-row :gutter='20'>
                      <el-col :span='20'>
                        <el-form-item label='名称' prop='name'>
                          <el-input v-model='formData.name' placeholder='请输入名称' clearable></el-input>
                        </el-form-item>
                      </el-col>
                    </el-row>

                    <el-row :gutter='20'>
                      <el-col :span='20'>
                        <el-form-item label='是否静态' prop='isEnable'>
                          <el-switch v-model='formData.isEnable' inline-prompt active-text='是' inactive-text='否'
                                     :active-value='1' :inactive-value='0'></el-switch>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row :gutter='20'>
                      <el-col :span='20'>
                        <el-form-item>
                          <el-button type='primary' @click='saveForm'>保存</el-button>
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </el-form>

                  <el-divider>模板修改记录</el-divider>

                  <vxe-table ref='templateRecordTable' border='inner' align='center' height='auto'
                             :data='templateRecordList'
                             :expand-config='{ expandAll: true, reserve: true }'
                             :row-config='{ isCurrent: true, isHover: true }'
                             :column-config='{ resizable: true }'
                             :keyboard-config='{ isArrow: true, isTab: true, isEdit: true }'
                             resizable show-overflow keep-source>
                    <vxe-column field='createTime' title='修改时间'></vxe-column>
                    <vxe-column field='sourceFileUrl' title='修改历史'>
                      <template #default='{ row }'>
                        <vxe-button status="primary" content="查看" icon='vxe-icon-eye-fill' class="modelViewBtn" @click='showTemplate(row.sourceFileUrl)'>
                        </vxe-button>
                      </template>
                    </vxe-column>
                  </vxe-table>

                </el-tab-pane>
              </el-tabs>
            </Pane>
          </Splitpanes>
        </el-tab-pane>
        <el-tab-pane label='操作日志'>
          <LogInfo requestUrl='/wk/quality/stage'></LogInfo>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup lang='ts'>
// 引入组件区 ==========
import Breadcrumb from '@/components/Breadcrumb.vue';
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import { Splitpanes, Pane } from 'splitpanes';
import { AppStore } from '@/stores/store';
import { IsEmpty } from '@/utils/common'
import { VxeNotifyType, VxeMessage } from '@/utils/CommonMessage';
import LuckyExcelForm from '@/components/LuckyExcel.vue';
import LogInfo from '@/components/LogInfo.vue';


// 全局变量定义区 ==========
let { proxy }: any = getCurrentInstance();
let tableRef: any = ref(null);
let store = AppStore();
let form = reactive({
  antName: '' //名称
});

// 基本信息form表单
let formData = reactive({
  id: '',
  code: '' /*编码*/,
  name: '' /*名称*/,
  isEnable: 1 /*是否静态*/
});

let showTemplateDialog = ref(false);

let stageTypeList: any = reactive([]); //表格列表
let templateRecordList: any = reactive([]);
let loading = ref(false); //查询按钮加载

let saveLoading = ref(false);

let refFormData: any = ref(null); //信息表单ref

let isEditTemplate = ref(false); //表单是否可以提交
// 方法定义区 =============

/**
 * 页面加载时
 */
onMounted(() => {
  findPageList();
});

/**
 * 获取表格数据
 */
function findPageList() {
  loading.value = true;
  stageTypeList.length = 0;
  const url = '/wk/quality/stage/type/page';
  let params = { searchValue: form.antName };
  proxy.$http.get(url, { params: params }).then((res: any) => {
    stageTypeList.push(...res.data);
    roleRowClick({
      row: stageTypeList[0],
      rowIndex: 0
    });
    loading.value = false;
  }).catch((err: any) => {
    loading.value = false;
    VxeMessage('搜索阶段类型列表异常', VxeNotifyType.error);
  });
}

function roleRowClick({ row, rowIndex }: any) {
  formData.id = row.id;
  formData.code = row.code;
  formData.name = row.name;
  formData.isEnable = row.isEnable;
  getTemplateRecordList(row.id);
  (proxy.$refs.tableRef as any).setCurrentRow(row);
}

function getTemplateRecordList(templateId) {
  templateRecordList.length = 0;
  const url = '/wk/quality/template/record/page';
  let params = { id: templateId, sourceType: 'WkQualityStageType' };
  proxy.$http.get(url, { params: params }).then((res: any) => {
    templateRecordList.push(...res.data);
  }).catch((err: any) => {
    VxeMessage('搜索阶段类型列表异常', VxeNotifyType.error);
  });
}

function insertEvent() {
  clearFormData();
}

/**
 * 提交表单
 */
function saveForm() {
  let url = '';
  // 判断添加和编辑接口
  let isAdd = true;
  if (IsEmpty(formData.id)) {
    url = '/wk/quality/stage/type/add';
  } else {
    isAdd = false;
    url = '/wk/quality/stage/type/update';
  }
  proxy.$http.post(url, formData).then((res: any) => {
    if (res.status.code === 1) {
      if (isAdd) {
        VxeMessage('新增成功', VxeNotifyType.success);
      } else {
        VxeMessage('修改成功', VxeNotifyType.success);
      }
      findPageList();
    } else {
      if (isAdd) {
        VxeMessage('新增失败', VxeNotifyType.error);
      } else {
        VxeMessage('修改失败', VxeNotifyType.error);
      }
      return;
    }
  }).catch((err: any) => {
    VxeMessage('新增异常', VxeNotifyType.error);
  });
  clearFormData(); //清空数据
}

function clearFormData() {
  formData.id = '';
  formData.code = '';
  formData.name = '';
  formData.isEnable = 1;
}

/**
 * 删除按钮
 */
function removeEvent(row: any) {
  const $table = tableRef.value;
  if (row.id) {
    const url = '/wk/quality/stage/type/delete';
    proxy.$http.post(url, { id: row.id }).then((res: any) => {
      findPageList();
      VxeMessage(res.status.msg, VxeNotifyType.success);
    }).catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
  } else {
    $table.remove(row);
  }
}

//模板ID
let templateId = ref('');

/**
 * 加载模板
 * @param row
 */
function editTemplate(row: any) {
  isEditTemplate = true;
  showTemplateDialog.value = true;
  templateId = row.id;
  refFormData?.value?.hiddenUpload(false);
  proxy.$nextTick(() => {
    refFormData?.value?.initExcel(row.fileUrl);
  });
}

function showTemplate(fileUrl: any) {
  isEditTemplate = false;
  showTemplateDialog.value = true;
  proxy.$nextTick(() => {
    refFormData?.value?.initExcel(fileUrl);
    refFormData?.value?.hiddenUpload(true);
  });

}

/**
 * 关闭弹窗
 */
function closeTemplateDialog() {
  showTemplateDialog.value = false;
}

/**
 * 提交模板
 */
function submitTemplateDialog() {
  refFormData?.value?.submitExcel((url: string) => {
    proxy.$http.post('/wk/quality/stage/type/saveUrl', { id: templateId, fileUrl: url }).then((res: any) => {
      if (res.status.code === 1) {
        VxeMessage('保存模板成功', VxeNotifyType.success);
      } else {
        VxeMessage('保存模板失败', VxeNotifyType.error);
      }
    }).catch((err: any) => {
      VxeMessage('保存模板异常', VxeNotifyType.error);
    });
  });
  showTemplateDialog.value = false;
}

</script>

<style lang='scss' scoped>
#QualityStageType {
  height: 100%;

  .bodyContent {
    height: calc(100% - 60px);

    .el-tabs {
      height: 100%;

      :deep(.el-tabs__content) {
        height: calc(100% - 39px);
        padding: 0px;

        .el-tab-pane {
          height: 100%;

          .area {
            background-color: $base-white;
          }

          // 附加按钮间距
          .button-blue,
          .button-red {
            margin: 5px 0 5px 5px;
          }

          // 查询按钮
          .SearchBtn {
            margin-right: 5px;
          }
          .modelViewBtn,.deleteBtn {
              border-radius: 5px;
          }

          .tableBox {
            height: calc(100% - 40px);
           
          }
          .el-form {
            padding-top: 15px;
          }
        }
      }
    }
  }
}

</style>

